package com.hxd.otc.module.my.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.hxd.otc.R;
import com.hxd.otc.base.permission.PermissionLazyFragment;
import com.hxd.otc.common.ApiConstants;
import com.hxd.otc.common.UserHelper;
import com.hxd.otc.common.enums.CardLevelEnum;
import com.hxd.otc.common.enums.YsApplyStatusEnum;
import com.hxd.otc.dialog.ForbiddenBankCardDialog;
import com.hxd.otc.dialog.MultipleBlocksDialog;
import com.hxd.otc.event.Event;
import com.hxd.otc.module.login.activity.LoginActivity;
import com.hxd.otc.module.login.bean.AccountBean;
import com.hxd.otc.module.my.activity.AccountInfoActivity;
import com.hxd.otc.module.my.activity.AdManagementActivity;
import com.hxd.otc.module.my.activity.AfficheActivity;
import com.hxd.otc.module.my.activity.ApplyActivity;
import com.hxd.otc.module.my.activity.BankCardActivity;
import com.hxd.otc.module.my.activity.ContactCustomerActivity;
import com.hxd.otc.module.my.activity.MerchantsOrderActivity;
import com.hxd.otc.module.my.activity.NoSenseBillActivity;
import com.hxd.otc.module.my.activity.SecurityCenterActivity;
import com.hxd.otc.module.my.activity.ShareThePromotionActivity;
import com.hxd.otc.module.my.activity.WebViewActivity;
import com.hxd.otc.module.my.bean.AppInfoBean;
import com.hxd.otc.module.my.bean.YsPreBean;
import com.hxd.otc.module.my.contract.MyContract;
import com.hxd.otc.module.my.presenter.MyPresenter;
import com.hxd.otc.module.wallet.activity.CoinRecordActivity;
import com.hxd.otc.module.wallet.activity.WalletActivity;
import com.hxd.otc.module.wallet.activity.WalletContactActivity;
import com.hxd.otc.utils.CommonUtil;
import com.hxd.otc.utils.ResourceUtil;
import com.hxd.otc.utils.UIUtils;
import com.hxd.otc.utils.download.DownloadManagerUtil;
import com.hxd.otc.utils.hyphenate.HyphenateKeFuUtil;
import com.hxd.otc.widget.MyItemView;
import com.hyphenate.chat.ChatClient;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.OnClick;
import io.rong.imkit.RongIM;
import io.rong.imkit.manager.IUnReadMessageObserver;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;

/**
 * 作  者 :  胡庆岭
 * 时  间 :  2018/6/4 17:13
 * 描  述 :  ${我的fragment}
 */
public class MyFragment extends PermissionLazyFragment<MyPresenter> implements MyContract.View, IUnReadMessageObserver {
    @BindView(R.id.tv_name)
    TextView mTvName;
    @BindView(R.id.tv_uid)
    TextView mTvUid;
    @BindView(R.id.tv_identity)
    TextView mTvIdentity;

    @BindView(R.id.miv_message_list)
    MyItemView mMivMessageList;
    @BindView(R.id.miv_check_version)
    MyItemView mivCheckVersion;

    @BindView(R.id.miv_help_center)
    MyItemView mMivHelpCenter;
    @BindView(R.id.miv_publish_ad)
    MyItemView mMivPublishAd;
    @BindView(R.id.miv_my_assets)
    MyItemView mMivMyAssets;
    @BindView(R.id.miv_payment_transaction_bill)
    MyItemView mivPaymentTransactionBill;
    @BindView(R.id.tv_please_login)
    TextView mTvPleaseLogin;
    @BindView(R.id.iv_head_more)
    ImageView ivHeadMore;


    public static final int REQUEST_CODE_MESSAGE = 123;
    private static final int REQUEST_CODE_APPLY = 2001;
    private int mNotifyUnReadNums;//未读通知和公告数量
    private int mRongCloudUnreadNums;//未读融云消息数
    private AppInfoBean mUpdateVersionInfo;

    private ForbiddenBankCardDialog mApplyFailDialog;

    MultipleBlocksDialog bindBankCardDialog;

    @Override
    protected void initView() {
        registerEventBus();
        mivCheckVersion.setRightText(getString(R.string.two_placeholder1, getString(R.string.my_fragment_v), CommonUtil.getVersionName()));
        updatePaymentTransactionBillUI();
    }

    @Override
    protected void initData() {
        updateAccountInfo(UserHelper.getUserInfo());
        getRongUnreadCount();
    }

    @Override
    protected void initEvent() {
        RongIM.getInstance().addUnReadMessageCountChangedObserver(this, Conversation.ConversationType.PRIVATE);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_my;
    }

    @Override
    protected MyPresenter createPresenter() {
        return new MyPresenter(this);
    }

    @OnClick({R.id.cl_user_info, R.id.miv_my_assets, R.id.miv_trading_mode, R.id.miv_publish_ad, R.id.miv_pay_list,
            R.id.miv_contact_customer_service, R.id.miv_security_center,
            R.id.miv_message_list, R.id.miv_contacts, R.id.miv_merchant_order, R.id.miv_help_center, R.id.miv_check_version,
            R.id.miv_share_the_promotion, R.id.miv_payment_transaction_bill})
    public void onClick(View view) {

        if (isNeedLogin(view.getId()) && !UserHelper.isLogin()) {
            $startActivity(LoginActivity.class);
            return;
        }

        switch (view.getId()) {
            case R.id.miv_my_assets://我的资产
                $startActivity(WalletActivity.class);
                break;
            case R.id.cl_user_info://
                $startActivity(AccountInfoActivity.class);
                break;
            case R.id.miv_trading_mode://账号设置
                goBankCardPage();
                break;
            case R.id.miv_publish_ad://发布广告
                onPublishAdvert();
                break;
            case R.id.miv_pay_list://支付账单
                $startActivity(CoinRecordActivity.class);
                break;
            case R.id.miv_contact_customer_service:
                onLineChat();
                break;
            case R.id.miv_security_center://安全中心
                onSecurityCenter();
                break;
            case R.id.miv_message_list://消息列表
                $startActivityForResult(AfficheActivity.class, REQUEST_CODE_MESSAGE);
                break;
            case R.id.miv_contacts://联系人
                onContacts();
                break;
            case R.id.miv_merchant_order://商户订单
                onMerchantsOrder();
                break;
            case R.id.miv_help_center://帮助中心
                onHelpCenter();
                break;
            case R.id.miv_check_version://版本更新
                doNewVersionUpdate();
                break;
            case R.id.miv_share_the_promotion://分享推广
                onSkipShareThePromotion();
                break;
            case R.id.miv_payment_transaction_bill://无感支付交易账单
                if (UserHelper.isNonInductivePaySilver() || UserHelper.isSilver()) {
                    $startActivity(NoSenseBillActivity.class);
                }
                break;
        }
    }

    private void goBankCardPage() {
        // 认证为V0，并且不是广告商 和商户时 ，不能进收款方式
        if (UserHelper.getCardLevel().equals(CardLevelEnum.LEVEL_0)) {
            if (bindBankCardDialog == null) {
                bindBankCardDialog = new MultipleBlocksDialog(getContext());
                bindBankCardDialog
//                        .setContent(getString(R.string.only_real_name_auth_can_bind_card))
                        .setTitlewithOutPading(getString(R.string.only_real_name_auth_can_bind_card))
//                        .setTitleGone()
                        .setTvSure(getString(R.string.go_to_real_name_auth), new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                bindBankCardDialog.dismiss();
                                onSecurityCenter();
                            }
                        });
            }
            bindBankCardDialog.show();
        } else {
            $startActivity(BankCardActivity.class);
        }
    }

    private void onPublishAdvert() {
        if (UserHelper.isSilver()) {
            $startActivity(AdManagementActivity.class);
            return;
        }
        YsPreBean ysPreBean = mPresenter.getYsPreBean();
        if (ysPreBean == null) return;

        YsApplyStatusEnum ysApplyStatusEnum = YsApplyStatusEnum.getInstance(ysPreBean.getStatus());
        if (ysApplyStatusEnum == null) {
            showToast(getString(R.string.abnormal_advertiser_status));
            return;
        }
        Bundle bundle = new Bundle();
        bundle.putSerializable(ApplyActivity.EXTRA_YS_APPLY_PRE, ysPreBean);
        if (YsApplyStatusEnum.NOT_APPLY.equals(ysApplyStatusEnum)) {//未认证
            $startActivityForResult(ApplyActivity.class, REQUEST_CODE_APPLY, bundle, false);
        } else if (YsApplyStatusEnum.APPLYING.equals(ysApplyStatusEnum)) {//审核中
            showToast(getString(R.string.your_bank_application_is_under_review));
            mPresenter.requestYsApplyPreInfo();//审核中点击重新再次获取广告商状态
        } else if (YsApplyStatusEnum.REJECT.equals(ysApplyStatusEnum)) {//被拒绝
            showApplyFailDialog(bundle, ysPreBean.getRemark());
        } else if (YsApplyStatusEnum.FREEZE.equals(ysApplyStatusEnum)) {//被冻结
            showToast(getString(R.string.your_advertisers_identity_has_been_frozen));
        }

    }

    /**
     * 广告商申请被拒绝提示对话框
     *
     * @param bundle
     * @param remark
     */
    private void showApplyFailDialog(final Bundle bundle, String remark) {
        if (mApplyFailDialog == null) {
            mApplyFailDialog = new ForbiddenBankCardDialog<String>(getContext())
                    .setTitle(getString(R.string.hint))
                    .setConfirmText(getString(R.string.recertification))
                    .setOnConfirmClickListener(new ForbiddenBankCardDialog.OnConfirmClickListener<String>() {
                        @Override
                        public void onConfirm(String advertId) {
                            $startActivityForResult(ApplyActivity.class, REQUEST_CODE_APPLY, bundle, false);
                        }
                    });
        }
        mApplyFailDialog.setMessage(TextUtils.isEmpty(remark) ? getString(R.string.your_advertisement_application_has_failed_do_you_want_to_re_authenticate_it) : remark);
        mApplyFailDialog.show();
    }

    private boolean isNeedLogin(int viewId) {
        switch (viewId) {
            case R.id.miv_help_center:
            case R.id.miv_check_version:
            case R.id.miv_contact_customer_service:
                return false;
            default:
                return true;
        }
    }

    private void onSkipShareThePromotion() {
        $startActivity(ShareThePromotionActivity.class);
    }

    private void onLineChat() {
        if (!ChatClient.getInstance().isLoggedInBefore()) {
            HyphenateKeFuUtil.getInstance().register();
        }
        $startActivity(ContactCustomerActivity.class);
    }

    private void doNewVersionUpdate() {
        if (DownloadManagerUtil.hasNewVersion(mUpdateVersionInfo, true)) {
            DownloadManagerUtil.showUpdateVersionDialog(getActivity(), mUpdateVersionInfo);
        } else {
            showToast(getString(R.string.this_is_the_latest_version));
        }
    }

    private void onAccountInfo() {
        $startActivity(AccountInfoActivity.class);
    }

    private void onSecurityCenter() {
        $startActivity(SecurityCenterActivity.class);
    }


    /**
     * 联系人
     */
    private void onContacts() {
        Bundle bundle = new Bundle();
        bundle.putBoolean(WalletContactActivity.EXTRA_IS_SHOW_ADD, true);
        $startActivity(WalletContactActivity.class, bundle);
    }

    /**
     * 商户订单
     */
    private void onMerchantsOrder() {
        $startActivity(MerchantsOrderActivity.class);
    }

    /**
     * 帮助中心
     */
    private void onHelpCenter() {
        Bundle bundle = new Bundle();
        bundle.putString(WebViewActivity.EXTRA_TITLE, getString(R.string.my_help_center));
        bundle.putString(WebViewActivity.EXTRA_URL, ApiConstants.URL_OF_HELP);
        bundle.putBoolean(WebViewActivity.EXTRA_IS_HELP_CENTER, true);
        $startActivity(WebViewActivity.class, bundle);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updateAccountInfoEvent(Event.UserInfoUpdateEvent userInfoUpdateEvent) {
        updateAccountInfo(userInfoUpdateEvent.getUserInfo());
    }

    @SuppressLint("DefaultLocale")
    @Override
    public void updateAccountInfo(AccountBean accountBean) {
        if (UserHelper.isLogin()) {
            String nickname = UserHelper.getNickName();
            String uid = UserHelper.isBoundPhone() ? UserHelper.getMobile() : UserHelper.getEmail();
            updatePaymentTransactionBillUI();
            if (TextUtils.isEmpty(nickname)) {
                mTvIdentity.setText("");
                mTvName.setText(R.string.please_set_the_nickname);
                mTvUid.setText(uid);
                mTvIdentity.setBackgroundResource(R.mipmap.icon_identity_not_login);
                mTvPleaseLogin.setVisibility(View.GONE);
                mTvName.setVisibility(View.VISIBLE);
                ivHeadMore.setVisibility(View.GONE);
                mTvUid.setVisibility(View.VISIBLE);
            } else {
                mTvIdentity.setText(nickname.substring(0, 1));
                mTvIdentity.setBackgroundResource(R.drawable.shape_circle_my_name_identity_bg);
                mTvPleaseLogin.setVisibility(View.GONE);
                mTvName.setText(nickname);
                mTvUid.setText(uid);
                mTvName.setVisibility(View.VISIBLE);
                mTvUid.setVisibility(View.VISIBLE);
                ivHeadMore.setVisibility(View.VISIBLE);
            }
            if (UserHelper.isSilver()) {
                updateYsApplyStatus(YsApplyStatusEnum.PASS);
            }
        } else {
            mTvIdentity.setText("");
            mTvIdentity.setBackgroundResource(R.mipmap.icon_identity_not_login);
            mTvPleaseLogin.setText(R.string.my_please_login);
            mTvPleaseLogin.setVisibility(View.VISIBLE);
            mTvName.setVisibility(View.GONE);
            mTvUid.setVisibility(View.GONE);
            ivHeadMore.setVisibility(View.GONE);
            updateYsApplyStatus(null);
        }
    }

    private void updatePaymentTransactionBillUI() {
        if (UserHelper.isNonInductivePaySilver() || UserHelper.isSilver()) {
            mivPaymentTransactionBill.setVisibility(View.VISIBLE);
        } else {
            mivPaymentTransactionBill.setVisibility(View.GONE);
        }
    }

    @SuppressLint("DefaultLocale")
    @Override
    public void notifyUnReadNum(Integer num) {
        mNotifyUnReadNums = num == null ? 0 : num;
        updateUnreadMessageNums();
    }

    @SuppressLint("DefaultLocale")
    private void updateUnreadMessageNums() {
        int totalUnreadNums = mNotifyUnReadNums + mRongCloudUnreadNums;
        if (totalUnreadNums > 0) {
            mMivMessageList.setRightText(String.format(getString(R.string.sub_unread_messages), totalUnreadNums));
        } else {
            mMivMessageList.setRightText("");
        }
    }

    @Override
    protected void lazyLoad() {
        super.lazyLoad();
        if (getUserVisibleHint()) {
            if (mUpdateVersionInfo == null) mPresenter.getUpdateVersionInfo();//当获取版本信息失败，则重新获取版本信息
            mPresenter.getUnreadMessageNums();//获取未读数
            if (UserHelper.isLogin() && !UserHelper.isSilver()) {
                mPresenter.requestYsApplyPreInfo();
            }
        }
    }

    /**
     * 获取融云未读消息数
     */
    private void getRongUnreadCount() {
        RongIMClient.getInstance().getUnreadCount(new RongIMClient.ResultCallback<Integer>() {
            @Override
            public void onSuccess(Integer integer) {
                mRongCloudUnreadNums = integer == null ? 0 : integer;
                updateUnreadMessageNums();
            }

            @Override
            public void onError(RongIMClient.ErrorCode errorCode) {
                mRongCloudUnreadNums = 0;
                updateUnreadMessageNums();
            }
        }, Conversation.ConversationType.PRIVATE);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_MESSAGE && resultCode == Activity.RESULT_OK) {
            mPresenter.getUnreadMessageNums();
        } else if (requestCode == REQUEST_CODE_APPLY) {
            mPresenter.requestYsApplyPreInfo();
        }
    }

    @Override
    public void onCountChanged(int i) {
        mRongCloudUnreadNums = i;
        updateUnreadMessageNums();
    }

    @Override
    public void getUpdateVersionInfoSuccess(AppInfoBean appInfoBean) {
        mUpdateVersionInfo = appInfoBean;
        if (DownloadManagerUtil.hasNewVersion(appInfoBean, true)) {
            mivCheckVersion.setRightText(ResourceUtil.getString(R.string.my_there_is_a_new_version, appInfoBean.getVersion()));
        } else {
            mivCheckVersion.setRightText(getString(R.string.two_placeholder1, getString(R.string.my_fragment_v), CommonUtil.getVersionName()));
        }
    }


    @Override
    public void getApplyBondInfoFail(String errMessage) {
        showToast(errMessage);
    }

    @Override
    public void updateYsApplyStatus(YsApplyStatusEnum ysApplyStatusEnum) {
        if (ysApplyStatusEnum == null) mMivPublishAd.setRightText("");
        mMivPublishAd.setRightText(ysApplyStatusEnum == null ? "" :
                YsApplyStatusEnum.PASS.equals(ysApplyStatusEnum) ? "" : ysApplyStatusEnum.getDesc());

        mMivPublishAd.setLeftText(getString(ysApplyStatusEnum == null ?
                R.string.advertiser_certification :
                YsApplyStatusEnum.PASS.equals(ysApplyStatusEnum) ?
                        R.string.my_publish_entry_orders :
                        R.string.advertiser_certification));
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        RongIM.getInstance().removeUnReadMessageCountChangedObserver(this);
        UIUtils.dismissDialog(mApplyFailDialog);
    }
}
